import axios, { AxiosInstance } from 'axios';

export interface AIServiceConfig {
    apiUrl: string;
    apiKey: string;
    systemPrompt: string;
}

export class AIService {
    private axiosInstance: AxiosInstance;
    private config: AIServiceConfig;

    constructor(config: AIServiceConfig) {
        this.config = config;
        this.axiosInstance = axios.create({
            baseURL: config.apiUrl,
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${config.apiKey}`
            }
        });
    }

    async sendMessage(message: string): Promise<Response> {
        const requestData = {
            model: 'deepseek-chat',
            messages: [
                {
                    role: 'system',
                    content: this.config.systemPrompt
                },
                {
                    role: 'user',
                    content: message
                }
            ],
            temperature: 0.7,
            max_tokens: 500,
            stream: true
        };

        // 使用fetch而不是axios来支持流式响应
        return fetch(this.config.apiUrl, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${this.config.apiKey}`,
                'Accept': 'text/event-stream'
            },
            body: JSON.stringify(requestData)
        });
    }

    // 用于非流式请求的方法
    async sendMessageNonStream(message: string) {
        const requestData = {
            model: 'deepseek-chat',
            messages: [
                {
                    role: 'system',
                    content: this.config.systemPrompt
                },
                {
                    role: 'user',
                    content: message
                }
            ],
            temperature: 0.7,
            max_tokens: 500
        };

        try {
            const response = await this.axiosInstance.post('', requestData);
            return response.data.choices[0].message.content;
        } catch (error) {
            console.error('发送消息时出错:', error);
            throw error;
        }
    }
}